<template>
  <base-breadcrumb :breadcrumb="!isAudit">
  <a-spin :spinning="tableLoading">
    <a-card>
      <titleName title="基本信息"></titleName>
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
        :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
      >
        <a-row :gutter="24">
            <a-col span="16">
            <a-form-model-item label="所属单位" prop="projectId">
              <org-tree-select
                               v-model="form.projectId"
                               :is-query-projec-detail="false"
                               checkStrictly
                               disabled
                              ></org-tree-select>
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="建筑面积(㎡)：" prop="constructionArea">
              <a-input-number
                :disabled="pageType == 'look'"
                :min="0"
                placeholder="请输入"
                v-model="form.constructionArea"
              />
            </a-form-model-item>
          </a-col>

          <a-col :md="8" :sm="8">
            <a-form-model-item label="中标价(不含税)(元)：" prop="projectId">
              <a-input v-model="form.items.inThePrice" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="标准成本(不含税)(元)：" prop="projectId">
              <a-input v-model="form.items.standardCost" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="标价分离率" prop="constructionArea">
              <a-input-number :precision="2" v-model="form.items.percentage" disabled />
            </a-form-model-item>
          </a-col>

          <a-col :md="8" :sm="8">
            <a-form-model-item label="间接费用占比（%）" prop="proportionOfExpensesRate">
              <a-input-number :precision="2" :max='1000' v-model="form.proportionOfExpensesRate"
                              :disabled="pageType == 'look' && $route.query.pageType !== 'haveRecord'"
                              placeholder="请输入" />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="标价分离时间：" prop="compleDate">
              <a-date-picker v-model="form.compleDate"
                             placeholder="请选择"
                             :disabled="pageType == 'look' && $route.query.pageType !== 'haveRecord'"
                             format="YYYY-MM-DD" value-format="YYYY-MM-DD"></a-date-picker>
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="中标时间：">
              <a-input v-model="winningTime" disabled></a-input>
            </a-form-model-item>
          </a-col>

          <a-col v-if="pageType != 'look'" :md="24" :sm="24">
            <a-form-model-item label="附件上传">
              <upload-list
                :businessCode="'BM19'"
                :uploadArrys.sync="form.fileInfoVOList"
                @fileArrysData="handleFileUploaded"
                multiple
              ></upload-list>
            </a-form-model-item>
          </a-col>
          <a-col :md="24" :sm="24" v-else>
            <a-form-model-item label="附件">
              <file-link :fileList="form.fileInfoVOList"></file-link>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>
    <a-card>
      <titleName title="数据填写"></titleName>
      <ExcelImportButton v-if="pageType !== 'look'" button-text="导入" icon="upload" @handleSubmit="importFunc"  class="mb12" />

      <excel v-if="pageType !== 'look'" ref="exportAll" file-name="标价分离" is-click-generate="false" class="mb12">
        <a-button slot="excelBtn" @click="exportAll"> 下载模板 </a-button>
      </excel>
      <s-table
        ref="table"
        size="default"
        rowKey="key"
        :columns="columns"
        :data="loadData"
        :alert="true"
        show-size-changer
        show-quick-jumper
        :showPagination="false"
        :scroll="{x:true}"
      >
        <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
        <template
          v-for="col in [
            'inThePrice',
            'outputTax',
            'standardCost',
            'inputTax',
            'difference',
            'percentage',
            'standardCostPrice'
          ]"
          :slot="col"
          slot-scope="text, record, index"
        >
          <div :key="col" class="requiredFormItem">
            <a-input-number
              v-if="index < form.itemList.length - 1"
              :value="text"
              :disabled="pageType == 'look' || col == 'difference' || col == 'percentage' || col == 'standardCostPrice'"
              :precision="2"
              placeholder="请输入"
              @change="e => handleInput(e, record.key, col)"
              style="width: 100%;"
            />
            <template v-else>{{ text ? text : '0.00' }}</template>
          </div>
        </template>
        <span slot="costName" slot-scope="text, record, index" class="requiredFormItem">
          <a-input
            v-if="index < form.itemList.length - 1"
            v-model="record.costName"
            :maxLength="9"
            :disabled="pageType == 'look'"
            style="width: 100%;"
          ></a-input>
          <span v-else>{{ text }}</span>
        </span>
        <span slot="unit" slot-scope="text, record, index" class="requiredFormItem">
          <a-input
            v-if="index < form.itemList.length - 1"
            v-model="record.unit"
            :disabled="pageType == 'look'"
            style="width: 100%;"
          ></a-input>
        </span>

        <span slot="actions" slot-scope="text, record, index">
          <div v-if="index < form.itemList.length - 1">
            <a :disabled="pageType == 'look'" @click="handleItem('add', {}, index)">加一行</a>
            <a-divider type="vertical" />
            <a :disabled="form.itemList.length == 2 || pageType == 'look'" @click="handleItem('del', record, index)"
              >移除</a
            >
          </div>
        </span>
      </s-table>
    </a-card>
    <div class="tool-btns page-btn-right-top" v-if="pageType != 'look' || $route.query.pageType === 'haveRecord'">
      <a-button type="primary" :disabled="!isSubmit" :loading="loading.DRAFT" @click="handleSave('DRAFT')"
                v-if="$route.query.pageType !== 'haveRecord'"
        >保存草稿</a-button
      >
      <a-button type="primary" :disabled="!isSubmit" :loading="loading.SUBMITTED" @click="handleSave('SUBMITTED')"
        >提交</a-button
      >
      <a-button type="primary" @click="handleClose">关闭</a-button>
    </div>
    <div class="tool-btns page-btn-right-top" v-else>
      <a-button type="primary" @click="handleClose" v-if="checkVisibleInDetail">关闭</a-button>
    </div>
    </a-spin>
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>
<script>
import { getProjectInfo } from '@/api/businessAffairs/revenueAndCost'
import {
  getQuotationList,
  addQuotationList,
  editQuotationList,
  delQuotationList,
  checkQuotationList,
} from '@/api/businessAffairs/priceSeparation'
import { getSelectListByType } from '@/api/businessAffairs/common.js'

import { isAttachment, checkVisibleInDetail } from '@/utils/util'
import { STable } from '@/components'
import UploadList from '@/components/UploadList'

const columns = [
  {
    title: '序号',
    dataIndex: 'serial',
    width: '65px',
    scopedSlots: { customRender: 'serial' }
  },

  {
    title: '费用名称',
    dataIndex: 'costName',
    width: '160px',
    scopedSlots: { customRender: 'costName' }
  },
  // {
  //     title: '单位',
  //     dataIndex: 'unit',
  //     scopedSlots: { customRender: 'unit' },
  // },
  {
    title: '中标价(不含税)(元)',
    dataIndex: 'inThePrice',
    scopedSlots: { customRender: 'inThePrice' }
  },
  {
    title: '销项税(元)',
    dataIndex: 'outputTax',
    scopedSlots: { customRender: 'outputTax' }
  },
  {
    title: '标准成本(不含税)(元)',
    dataIndex: 'standardCost',
    scopedSlots: { customRender: 'standardCost' }
  },
  {
    title: '进项税(元)',
    dataIndex: 'inputTax',
    scopedSlots: { customRender: 'inputTax' }
  },
  {
    title: '差额(元)',
    dataIndex: 'difference',
    scopedSlots: { customRender: 'difference' }
  },
  {
    title: '节(+)超(-)(%)',
    dataIndex: 'percentage',
    scopedSlots: { customRender: 'percentage' }
  },
  {
    title: '标准成本平米单价(不含税)(元/m2)',
    dataIndex: 'standardCostPrice',
    width: '200px',
    scopedSlots: { customRender: 'standardCostPrice' }
  },
  {
    title: '操作',
    dataIndex: 'actions',
    width: '170px',
    fixed: 'right',
    scopedSlots: { customRender: 'actions' }
  }
]
const columnsLook = [
  {
    title: '序号',
    dataIndex: 'serial',
    width: '5%',
    scopedSlots: { customRender: 'serial' }
  },

  {
    title: '费用名称',
    dataIndex: 'costName',
    scopedSlots: { customRender: 'costName' }
  },
  // {
  //     title: '单位',
  //     dataIndex: 'unit',
  //     scopedSlots: { customRender: 'unit' },
  // },
  {
    title: '中标价(不含税)(元)',
    dataIndex: 'inThePrice',
    scopedSlots: { customRender: 'inThePrice' }
  },
  {
    title: '销项税(元)',
    dataIndex: 'outputTax',
    scopedSlots: { customRender: 'outputTax' }
  },
  {
    title: '标准成本(不含税)(元)',
    dataIndex: 'standardCost',
    scopedSlots: { customRender: 'standardCost' }
  },
  {
    title: '进项税(元)',
    dataIndex: 'inputTax',
    scopedSlots: { customRender: 'inputTax' }
  },
  {
    title: '差额(元)',
    dataIndex: 'difference',
    scopedSlots: { customRender: 'difference' }
  },
  {
    title: '节(+)超(-)(%)',
    dataIndex: 'percentage',
    scopedSlots: { customRender: 'percentage' }
  },
  {
    title: '标准成本平米单价(不含税)(元/m2)',
    dataIndex: 'standardCostPrice',
    scopedSlots: { customRender: 'standardCostPrice' }
  }
]
export default {
  name: 'a' + Date.now(),
  components: {
    STable,
    UploadList
  },
  props: {
    isAudit: {
      // 是否作为审批详情
      type: Boolean,
      default: false
    }
  },
  watch: {
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.pageType = 'look'
          })
        }
      }
    }
  },
  data() {
    this.columns = columns
    return {
      winningTime: '',
      timeout: '',
      checkVisibleInDetail: checkVisibleInDetail(this),
      loading: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false
      },
      form: {
        constructionArea: '',
        fileInfoVOList: [],
        itemList: [],
        items: {
          inThePrice: 0,
          standardCost: 0,
          percentage: 0, //标价分离率
          compleDate: '',
          proportionOfExpensesRate: ''
        }
      },
      key: 0,
      rules: {
        constructionArea: [{ required: true, message: '请输入面积' }],
        compleDate:  [{ required: true, message: '请选择标价分离时间' }],
        proportionOfExpensesRate:  [{ required: true, message: '请输入间接费用占比' }],
      },
      id: '',
      isSubmit: true,
      pageType: '',
      tableLoading: false,
      loadData: () => {
        if (this.form.itemList.length > 0) {
          return new Promise((resolve, reject) => {
            resolve({
              data: this.form.itemList
            })
          })
        }
      },
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null,
      isChange: false
    }
  },

 async mounted() {
    if (this.$route.query.id) {
      this.id = this.$route.query.id
      this.checkQuotationListReq()
    }
    this.pageType = this.$route.query.pageType
    if(this.$route.query.pageType === 'haveRecord') {
      this.pageType = 'look'
    }
    if (this.pageType == 'look') {
      this.columns = columnsLook
    }

    if (this.pageType == 'add') {
      this.getSelectListByTypeReq()
    }
    let theme = {
      序号: 'serial',
      费用名称: 'costName',
      '中标价(不含税)(元)': 'inThePrice',
      '销项税(元)': 'outputTax',
      '标准成本(不含税)(元)': 'standardCost',
      '进项税(元)': 'inputTax'
    }
    this.$refs.exportAll.setExcelFields(theme)
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('comm_price_separation_book_new')
  },

  methods: {
    //导出
    exportAll: function() {
      // 参数：查询条件、导出的回调
      this.list(false, this.$refs.exportAll.setDataAndGenerate)
    },
    list(params, callback) {
      this.loading = true
      if (this.$route.query.id) {
        //详情页面
        this.checkQuotationListReq()
        if (callback) {
          let data = this.form.itemList.map((items, index) => {
            items.serial = index + 1
            items.inThePrice = items.inThePrice.toString()
            items.outputTax = items.outputTax.toString()
            items.standardCost = items.standardCost.toString()
            items.inputTax = items.inputTax.toString()
            items.key = items.key.toString()
            return items.costName !== '合计' ? items : false
          })
          callback(data)
        }
      } else {
        //新增页面
        if (callback) {
          let data = this.form.itemList.map((items, index) => {
            items.serial = index + 1
            items.inThePrice = items.inThePrice.toString()
            items.outputTax = items.outputTax.toString()
            items.standardCost = items.standardCost.toString()
            items.inputTax = items.inputTax.toString()
            items.key = items.key.toString()
            return items.costName !== '合计' ? items : false
          })
          callback(data)
        }
      }
    },

    /**
     * 设置表格内容并手动生成excel文件并下载
     * exData 文件内容(JSON格式) tableObj 表格对象，startIndex 表格导出开始位置，默认为1
     */
    setDataAndGenerate: function(exData) {
      if (!exData) {
        return false
      }
      this.setExcelData(exData)
      var _this = this
      setTimeout(function() {
        _this.generate()
      }, 50)
    },

    handleFileUploaded(list) {
      this.form.fileInfoVOList = [...list]
    },
    async getSelectListByTypeReq(e) {
      this.$refs.table.localLoading = true
      const [err, res] = await getSelectListByType({ type: 16, enabled: true, needCount: false })
      this.$refs.table.localLoading = false
      if (!err) {
        res.data.forEach((item, index) => {
          this.form.itemList.push({
            costName: item.name,
            unit: '',
            inThePrice: 0,
            outputTax: 0,
            standardCost: 0,
            inputTax: 0,
            difference: 0,
            percentage: 0,
            standardCostPrice: 0,
            key: this.key
          })
          this.key++
        })
        this.getCombined()
        this.$refs.table.refresh(true)
      }
    },
    handleInput(value, key, column) {
      let that = this
      // if (this.timeout != '') {
      //   clearTimeout(this.timeout)
      // }
      const newData = [...that.form.itemList]
      const target = newData.filter(item => key === item.key)[0]
      if (target) {
        target[column] = value
        that.form.itemList = newData
      }
      // this.timeout = setTimeout(function() {
        that.form.itemList.pop()
        that.getCombined(false)
      // }, 1000)
    },
    getCombined(flag=true) {
      // this.form.itemList.pop()
      this.key++
      let inThePriceVal = this.sum(this.form.itemList, 'inThePrice'),
        standardCostVal = this.sum(this.form.itemList, 'standardCost'),
        percentage = (inThePriceVal - standardCostVal) / inThePriceVal
      this.form.items = {
        inThePrice: inThePriceVal,
        standardCost: standardCostVal,
        percentage: inThePriceVal != 0 ? percentage : 0.0
      }
      this.form.itemList.push({
        costName: '合计',
        unit: '',
        inThePrice: this.sum(this.form.itemList, 'inThePrice'),
        outputTax: this.sum(this.form.itemList, 'outputTax'),
        standardCost: this.sum(this.form.itemList, 'standardCost'),
        inputTax: this.sum(this.form.itemList, 'inputTax'),
        difference: this.sum(this.form.itemList, 'difference'),
        percentage: this.sum(this.form.itemList, 'percentage'),
        standardCostPrice: this.sum(this.form.itemList, 'standardCostPrice'),
        key: this.key
      })
      this.form.itemList.forEach(item => {
        item.difference = item.inThePrice - Number(item.standardCost).toFixed(2)
        if (this.form.constructionArea > 0 && item.standardCost > 0) {
          item.standardCostPrice =
            Number(item.standardCost / parseFloat(this.form.constructionArea)).toFixed(2) != 'NaN'
              ? (item.standardCost / parseFloat(this.form.constructionArea)).toFixed(2)
              : 0
        } else {
          item.standardCostPrice = 0
        }
        if (item.inThePrice > 0) {
          item.percentage =
            ((item.difference / item.inThePrice) * 100).toFixed(2) != 'NaN'
              ? ((item.difference / item.inThePrice) * 100).toFixed(2)
              : 0
        } else {
          item.percentage = 0
        }
      })
      if(flag) {
        this.$refs.table.refresh(true)
      } else {
        this.$refs.table.localDataSource = this.form.itemList
      }
      this.$forceUpdate()
    },
    sum(arr, str) {
      let sum = 0
      for (let i = 0; i < arr.length; i++) {
        if (arr[i][str] == null) {
          arr[i][str] = 0
        }
        sum += parseFloat(arr[i][str])
      }
      return sum.toFixed(2)
    },
    handleItem(type, data, index) {
      if (type == 'add') {
        this.key++
        this.form.itemList.splice(index + 1, 0, {
          costName: '',
          unit: '',
          inThePrice: 0,
          outputTax: 0,
          standardCost: 0,
          inputTax: 0,
          difference: 0,
          percentage: 0,
          standardCostPrice: 0,
          key: this.key
        })
      } else {
        this.form.itemList.forEach((item, index) => {
          if (item.key == data.key) {
            this.form.itemList.splice(index, 1)
          }
        })
        this.form.itemList.pop()
        this.getCombined()
      }
      this.$refs.table.refresh(true)
    },
    getTime(date, dateString, type, name) {
      this[type][name] = dateString
    },
    //判断该项目是否可添加次业务
    async getIsProject(e) {
      const [err, res] = await getQuotationList({ projectId: e, enter: true })
      if (res.data.length > 0 && this.id != res.data[0].id) {
        this.isSubmit = false
        this.$message.warning('标价分离书在该项目已存在，不可再次添加')
      } else {
        this.isSubmit = true
      }
    },
    async checkQuotationListReq() {
      this.tableLoading = true;
      const [err, res] = await checkQuotationList({ id: this.id })
      if (!err) {
        getProjectInfo({ projectId: res.data.projectId }).then(res => {
          if(!this.form.constructionArea) {
            this.$set(this.form, 'constructionArea', res.data.contractTotalArea * 100 * 100)
          }
          this.winningTime = res.data.winningTime
        })
        this.tableLoading = false;
        if(res.data.itemList) {
          res.data.itemList.forEach(item => {
            this.key++
            item.key = this.key
          })
        } else {
          this.form.projectId = res.data.projectId
          this.form.id = res.data.id
         this.getSelectListByTypeReq()
          return
        }
        this.form = res.data
        // this.handleChange(this.form.projectId)
        this.getCombined()
        // this.$refs.table.refresh(true)
      }else {
        this.tableLoading = false;
      }
    },
    validateForm() {
      let flag = false
      this.$refs.ruleForm.validate(valid => {
        flag = valid
        if(!valid) {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
      return flag
    },
    // 处理增、删、改操作
    async handleSave(status) {
      this.setProcessConfig = null;
      if (this.loading[status]) return
      if (status != 'DELETE') {
        if (!this.validateForm()) return
        // if (isAttachment(this, status, this.form.fileInfoVOList)) return
      }
      // this.form.fileInfoVOList = []
      this.form.auditStatus = status

      this.form.itemList.forEach((item, index) => {
        item.index = index
      })
      let params = Object.assign(
        {},
        this.$clone(this.form)
        // { auditStatus: status == 'DRAFT' ? 0 : 1 }
        // id: this.$route.query.id || void 0,
      )
      params.itemList.pop()
      const { pageType } = this.$route.query
      const fn = (pageType === 'edit' || pageType === 'haveRecord') ? editQuotationList : addQuotationList
      const delParams = {id:params.id}
      const map = {
        DELETE: delQuotationList,
        DRAFT: fn,
        SUBMITTED: fn,
        REJECTED: fn
      }

      if (status == 'DELETE') {
        let that = this
        this.$confirm({
          title: '温馨提示',
          content: '确定是否删除数据？',
          okText: '确认',
          okType: 'danger',
          cancelText: '取消',
          onOk: () => {
            return that.delQuotationList(delParams)
          }
        })
        this.loading[status] = false
      } else {
        this.submitApprovalConfirm(status =='SUBMITTED'?this.processConfig:6, async (flag)=>{
          if(!flag) {
            this.loading[status] = true
            return
          }
        this.loading[status] = true
          params.informant = this.$userInfo().name
        const [err, res] = await map[status](params)
        if (!err) {
          this.$message.success('成功')
           if(status =='SUBMITTED') {
            //提交时，返回id
                this.businessId = res.data.id;
                this.setProcessConfig = this.processConfig;
                return
            }else{
            this.handleClose()
          }
        }
          this.loading[status] = false
        })
      }
    },
    async delQuotationList(params) {
      const [err, res] = await delQuotationList(params)
      if (!err) {
        this.$message.success('删除成功')
        this.handleClose()
      }
    },
    handleClose() {
      if (this.isAudit) {
        window.close()
      } else {
        this.$multiTab.close(this.$route.fullpath)
      }

      //  history.go(-1)
    },
    async importFunc(e) {
      let newTable = [],
        newTableTit = [],
        colEmpty = [],
        emptyTip = '',
        noneColArr = []
      e.map((row, num) => {
        let temp = {}
        newTableTit[num] = []
        for (const rowKey in row) {
          newTableTit[num].push(rowKey)
          let column = this.columns.find(columnRow => columnRow.title === rowKey)
          if (column) {
            let dataIndex = column.dataIndex
            temp[dataIndex] = row[rowKey]
          }
        }
        temp.settleId = this.id
        newTable.push(temp)
        //验证未填项
        let col = ['费用名称', '中标价(不含税)(元)', '销项税(元)', '标准成本(不含税)(元)', '进项税(元)']
        noneColArr[num] = []
        col.forEach((item, index) => {
          let status = newTableTit[num].includes(item)
          if (!status) {
            noneColArr[num].push(item)
          }
        })
        if (noneColArr[num].length > 0) {
          colEmpty[num] = {
            name: noneColArr[num],
            num: num + 1
          }
        }
      })
      this.form.itemList = newTable
      this.getCombined()
    }
  }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';
.tool-btns {
  display: flex;
  justify-content: flex-end;
  @{deep} .ant-btn + .ant-btn {
    margin-left: 12px;
  }
}
</style>
